package com.thoughtworks.android.androsphere.service.c2dm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class C2DMServiceHelper {
    public void delayCurrentThreadBy(Long delayInMilliseconds) {
        try {
            Thread.sleep(delayInMilliseconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Long computeTimeForExponentiallyBackingOff(long noOfFailureAttempts) {
        final double delayInMilliSecs = (Math.pow(2, noOfFailureAttempts) - 1) * 0.0512;
        return (long)delayInMilliSecs;
    }

    public Map<String, C2DMErrorResponseEnum> getResponseMap(InputStream inputStream) {
        Map<String, C2DMErrorResponseEnum> responseMap = new HashMap<String, C2DMErrorResponseEnum>();
        try {
            String responseLine = new BufferedReader(new InputStreamReader(inputStream)).readLine();
            String[] responseParts = responseLine.split("=", 2);
            if (responseParts[0].equals("Error")) {
                 responseMap.put("Error", C2DMErrorResponseEnum.getType(responseParts[1].trim()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMap;
    }
}
